import {
  getTargetSaleStatus,
  registerUser,
  getCommonStatus,
  getPhoneNumberData,
} from "./utils";
import { REGISTER_USER_TYPE, getMessageModalTemplate } from "./static";
import RegisterTracker from "./RegisterTracker";
import { getTabInfo } from "../../utils/commonFunction"

class RegisterController {
  userType = REGISTER_USER_TYPE.NEW_USER;
  phoneNumber = "";
  canRegister = false;

  changeUserType(userType) {
    this.userType = userType || REGISTER_USER_TYPE.NEW_USER;
  }

  async newUserCheck(phoneNumber) {
    this.userType = REGISTER_USER_TYPE.NEW_USER;
    return await this.execUserCheck(phoneNumber);
  }

  async oldUserCheck(phoneNumber) {
    this.userType = REGISTER_USER_TYPE.OLD_USER;
    return await this.execUserCheck(phoneNumber);
  }

  async execUserCheck(phoneNumber, templateType = "NORMAL") {
    const p = phoneNumber || this.phoneNumber;
    this.phoneNumber = p;
    const res = await getCommonStatus(p, this.userType);
    const template = getMessageModalTemplate(
      templateType,
      res.messageModalCode
    );
    if (template?.doRegister) {
      const registerData = await this.register(p);
      Object.assign(res, registerData);
    }
    res.phoneNumber = p;
    return res;
  }

  // 重新执行上一次的 userCheck, 保留上一次的userType
  async repeatUserCheck(phoneNumber) {
    if (this.userType === REGISTER_USER_TYPE.OLD_USER) {
      return await this.oldUserCheck(phoneNumber);
    } else {
      return await this.newUserCheck(phoneNumber);
    }
  }

  // 注册
  async register(phoneNumber) {
    const p = phoneNumber || this.phoneNumber;
    const res = await registerUser(p);
    res.phoneNumber = p;
    if (res.joinMemberSuccess) {
      // 注册成功, 刷新tabbar
      getTabInfo();
    }
    return res;
  }

  // 基于授权手机号查询TS活动状态
  async getTargetSaleStatus(phoneNumber, tsActId) {
    const res = await getTargetSaleStatus(phoneNumber, tsActId);
    this.canRegister = res.canRegister;
    return res;
  }

  // 解密手机号
  async getPhoneNumberData(getPhoneNumberEv, opt = {}) {
    const { noTips, location, tsActId } = opt;
    const res = await getPhoneNumberData(getPhoneNumberEv, noTips);
    if (res.success) {
      // 存下来, 准备跨组件调用
      this.phoneNumber = res.data.phoneNumber;
    }
    RegisterTracker.authMobile({
      agree: res.success,
      location,
      registerType: tsActId ? "TARGET_SALES" : "NORMAL",
    });
    return res;
  }
}

export default new RegisterController();
